<script setup lang="ts">
import { ref, onBeforeMount } from "vue";
import { deleteDict, queryDictChild } from "@/api/dict.js";

//引入组件
import addGroup from "./AddGroup.vue";
import dictList from "./DictList.vue";
import { ElMessage, ElMessageBox } from "element-plus";
//标签页哪个是激活的
const activeName = ref();

//是否显示新增
const isShow = ref(false);
//标签页
const tabsOptions = ref([]);
//子组件绑定
const saveUpdate = ref();

//标签是否可以关闭
const closable = ref(false);

//根据父id查询字典
async function queryDict() {
  let res = await queryDictChild(0);
  if (res.code == 200) {
    tabsOptions.value = res.data;
    //列表中第一项作为默认
    if (tabsOptions.value.length > 0) {
      let tmp = tabsOptions.value[0];
      activeName.value = tmp.code;
    }
  }
}

//删除字典
function deleteTypeByCode(targetName) {
  // 从 tabsOptions 中找到对应 code 的项
  const targetTab = tabsOptions.value.find(item => item.code === targetName);
  if (!targetTab) {
    ElMessage({
      type: "error",
      message: "未找到要删除的标签信息"
    });
    return;
  }

  const targetId = targetTab.id;
  console.log(targetId);
  ElMessageBox.confirm("确定要删除数据？", "删除", {
    confirmButtonText: "删除",
    cancelButtonText: "关闭",
    type: "warning"
  })
    .then(async () => {
      let res = await deleteDict(targetId);
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        // 在删除成功后调用 initData 函数刷新页面数据
        queryDict();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
      // 在删除成功后调用 initData 函数刷新页面数据
      queryDict();
    });
}

//添加的时候调用
function add() {
  isShow.value = true;
  saveUpdate.value.init();
}

//生命周期
onBeforeMount(() => {
  queryDict();
});
</script>

<template>
  <div class="root">
    <el-tabs
      v-model="activeName"
      type="card"
      class="demo-tabs"
      closable
      addable
      @tab-add="add"
      @tab-remove="deleteTypeByCode"
    >
      <template v-for="item in tabsOptions" :key="item.code">
        <el-tab-pane :label="item.name" :name="item.code">
          <dictList :pid="item.id" />
        </el-tab-pane>
      </template>
    </el-tabs>
    <!--  引入组件-->
    <addGroup
      ref="saveUpdate"
      :visible="isShow"
      @refreshData="queryDict"
      @close="isShow = false"
    />
  </div>
</template>

<style scoped lang="scss">
.root {
  height: 100%;
  background-color: #fff;
}
</style>
